package cn.lang.oss.factory;

import cn.lang.oss.Oss;
import cn.lang.oss.QiniuOss;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @ClassName : QiniuOssFactory
 * @Description : 七牛云工厂
 * @Author : Lang
 * @Date: 2020-03-07 08:53
 */
public class QiniuOssFactory implements IOssFactory{


    private static QiniuOss qiniuOss;
    /**
     * AccessKey的值
     */
    private  String accessKey;
    /**
     * SecretKey的值
     */
    private  String secretKey;
    /**
     *  存储空间名
     */
    private  String bucket;

    private  String domain;

    public QiniuOssFactory(){
        init();
    }

    public QiniuOssFactory(String accessKey,String secretKey,String bucket,String domain){
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        this.domain = domain;
    }


    void init(){
        Properties resouce = getResouce();
        if(resouce==null){
            throw new RuntimeException("不能获取到配置文件oss.properties");
        }
        this.accessKey = resouce.getProperty("qiniu.accessKey");
        this.secretKey = resouce.getProperty("qiniu.secretKey");
        this.bucket = resouce.getProperty("qiniu.bucket");
        this.domain = resouce.getProperty("qiniu.domain");
    }

    private Properties getResouce(){
        // 获取输入流
        InputStream in = getClass().getClassLoader().getResourceAsStream("oss.properties");
        // 新建配置对象
        Properties p = new Properties();
        // 通过输入流加载
        try {
            p.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 读取key
        return  p;
    }

    public static QiniuOssFactory create(){
        return new QiniuOssFactory();
    }


    public Oss getOss() {
        if(qiniuOss!=null){
            return qiniuOss;
        }
        QiniuOss qiniuOss = new QiniuOss(this.accessKey,this.secretKey,this.bucket,this.domain);
        QiniuOssFactory.qiniuOss = qiniuOss;
        return qiniuOss;
    }

    public Oss getOss(String accessKey,String secretKey,String bucket,String domain) {
        QiniuOss qiniuOss = new QiniuOss(accessKey,secretKey,bucket,domain);
        QiniuOssFactory.qiniuOss = qiniuOss;
        return qiniuOss;
    }

}
